package com.ai.zuochengyun.phase01.class03;

import java.util.Stack;

/**
 * 用栈实现队列
 */
public class Code03_StackImplementQueue {

    public static void main(String[] args) {
        TwoStackQueue<Integer> myQueue = new TwoStackQueue<>();
        myQueue.push(1);
        myQueue.push(2);
        myQueue.push(3);
        myQueue.push(4);
        myQueue.push(5);

        myQueue.pop();
        myQueue.peek();
        myQueue.push(6);
        myQueue.pop();
        myQueue.peek();
        myQueue.push(7);
        myQueue.pop();

        while (!myQueue.isEmpty()) {
            myQueue.pop();
        }


    }

    public static class TwoStackQueue<T> {
        private Stack<T> pushStack;
        private Stack<T> popStack;

        public TwoStackQueue() {
            pushStack = new Stack<>();
            popStack = new Stack<>();
        }

        /**
         * 将push栈中的数据导入到pop栈中
         * 需要遵循两个原则：
         * 1、一次性全部倒完
         * 2、pop栈必须是空的情况下，才能允许倒数据
         */
        private void pushToPop() {
            if(popStack.isEmpty()) {
                while (!pushStack.isEmpty()) {
                    popStack.push(pushStack.pop());
                }
            }
        }

        public void push(T value) {
            pushStack.push(value);
            pushToPop();
        }

        public T pop() {
            if (pushStack.isEmpty() && popStack.isEmpty()) {
                return null;
            }
            pushToPop();
            T ans = popStack.pop();
            System.out.println(ans);
            return ans;
        }

        public T peek() {
            if (pushStack.isEmpty() && popStack.isEmpty()) {
                return null;
            }
            pushToPop();
            T ans = popStack.peek();
            System.out.println(ans);
            return ans;
        }

        public boolean isEmpty() {
            return popStack.isEmpty() && pushStack.isEmpty();
        }

    }
}
